import React from "react";
import { NextPage } from "next";
import RSS from "@/rss/index.js";
import { ArticleApi } from "@/api/article";
import { SettingApi } from "@/api/setting";
import { CategoryApi } from "@/api/categroy";
const url = require("url");

const Rss: NextPage = () => {
  return null;
};

// 服务端预取数据
Rss.getInitialProps = async (ctx) => {
  const { res } = ctx;
  res.setHeader("Content-Type", "text/xml");

  let [articles, setting, categories] = await Promise.all([
    ArticleApi.getArticles({
      page: 1,
      pageSize: 99999,
      status: "publish",
    }),
    SettingApi.getSettings(),
    CategoryApi.getAll({ articleStatus: "publish" }),
  ]);

  const feed = new RSS(
    {
      title: setting.systemTitle,
      description: setting.seoDesc,
      feed_url: url.resolve(setting.systemUrl, "rss"),
      site_url: setting.systemUrl,
      author: "https://github.com/Owner-X",
      categories: categories.map((c) => c.label),
    },
    []
  );

  articles[0].forEach((article) => {
    feed.item({
      title: article.title,
      description: article.summary,
      url: url.resolve(setting.systemUrl, "article/" + article.id),
      date: article.publishAt,
      categories: [(article.category || {}).label],
    });
  });

  res.write(feed.xml(0));
  res.end();
};

export default Rss;
